#!/bin/bash
# script name: MySQL数据增幅监测脚本
# author: subushi
# update date: 2025.07.30

# 1. 定义变量
MONITOR_DIR="/data/compose/mysql"   # 需要监测的数据库
LOG_FILE="/opt/pre_monitor/mysql/mysql_size_history.log"   # 监测输出的记录
DATETIME=$(date +"%Y-%m-%d %H:%M")
HEADER="日期                  | 当前总大小  | 日增幅        | 增幅百分比"
DISK_LABEL="                 【MySQL数据目录：${MONITOR_DIR}】"

# 2. 检查目录是否存在
if [ ! -d "$MONITOR_DIR" ]; then
    echo "[$DATETIME] ERROR: 目录 $MONITOR_DIR 不存在！" >> "$LOG_FILE"
    exit 1
fi

# 3. 确保日志目录存在
mkdir -p "$(dirname "$LOG_FILE")"

# 4. 获取当前目录大小（带GB单位，保留3位小数）
CURRENT_SIZE_RAW=$(du -sb "$MONITOR_DIR" | awk '{printf "%.3f", $1 / 1024 / 1024 / 1024}')
CURRENT_SIZE="${CURRENT_SIZE_RAW}GB"

# 5. 计算日增幅（带GB单位）
PREVIOUS_SIZE_RAW=0
if [ -f "$LOG_FILE" ]; then
    # 提取前一天的"当前总大小"（去除GB单位，取数值部分）
    PREVIOUS_SIZE_RAW=$(tail -n +3 "$LOG_FILE" | tail -n 1 | awk -F '|' '{gsub(/GB| /,""); print $2}')
fi

# 计算增幅（带单位GB）
if [ $(echo "$PREVIOUS_SIZE_RAW == 0" | bc) -eq 1 ]; then
    GROWTH="--"
    GROWTH_PERCENT="--"
else
    GROWTH_RAW=$(echo "scale=3; $CURRENT_SIZE_RAW - $PREVIOUS_SIZE_RAW" | bc)
    GROWTH="${GROWTH_RAW}GB"
    GROWTH_PERCENT=$(echo "scale=2; ($GROWTH_RAW / $PREVIOUS_SIZE_RAW) * 100" | bc)
    GROWTH_PERCENT="${GROWTH_PERCENT}%"
fi

# 6. 写入日志文件
if [ ! -f "$LOG_FILE" ]; then
    echo "$DISK_LABEL" > "$LOG_FILE"
    echo "$HEADER" >> "$LOG_FILE"
    printf "%-22s| %-11s | %-13s | %s\n" \
        "$DATETIME" \
        "$CURRENT_SIZE" \
        "$GROWTH" \
        "$GROWTH_PERCENT" >> "$LOG_FILE"
elif ! grep -q "$DISK_LABEL" "$LOG_FILE"; then
    # 旧文件添加标识
    sed -i "1i $DISK_LABEL" "$LOG_FILE"
else
    # 追加数据行（与表头对齐）
    printf "%-22s| %-11s | %-13s | %s\n" \
        "$DATETIME" \
        "$CURRENT_SIZE" \
        "$GROWTH" \
        "$GROWTH_PERCENT" >> "$LOG_FILE"
fi

# 7. 输出执行结果
echo "✅ MySQL目录监控：$DATETIME - 当前大小: $CURRENT_SIZE, 日增幅: $GROWTH ($GROWTH_PERCENT)"